<template>
  <div id="nav">
    <myUpload
      field="file"
      :width="300"
      :height="300"
      v-model="isupload"
      img-format="png"
      @crop-success="success"
      :headers="headers"
      url="http://localhost:8000/user/upload"
    ></myUpload>
    <h3>TODO</h3>
    <div id="user">
      <span style="font-weight: bolder">{{ username }}</span>
      <div class="img">
        <img :src="userimg" alt="头像" @click="toggleshow" />

        <div class="userselect">
          <ul>
            <li @click="useredit">账号管理</li>
            <li @click="logout">退出登录</li>
          </ul>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import myUpload from 'vue-image-crop-upload/upload-2.vue';
export default {
  data() {
    return {
      username: '',
      userimg: '',
      isupload: false,
      headers: { Authorization: 'Bearer ' + localStorage.getItem('token') },
    };
  },
  components: { myUpload },
  methods: {
    toggleshow() {
      this.isupload = !this.isupload;
    },
    success(imgdataurl, field) {
      this.userimg = imgdataurl;
    },

    logout() {
      localStorage.removeItem('token');
      location.reload();
    },
    useredit() {
      this.$emit('useredit');
    },
  },
  async created() {
    let res = await this.axios.get('/user/img', {
      responseType: 'arraybuffer',
    });
    let imgBase64 =
      'data:image/png;base64,' +
      window.btoa(String.fromCharCode(...new Uint8Array(res.data)));
    this.userimg = imgBase64;
  },
  watch: {
    '$store.state.user.name'(after, before) {
      this.username = after;
    },
  },
};
</script>

<style scoped>
#nav {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: space-around;
}

.img {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  overflow: hidden;
}
img {
  width: 100%;
  height: 100%;
}
#user {
  width: 120px;
  height: 100%;
  display: flex;
  justify-content: space-around;
  align-items: center;
  position: relative;
}
#user span {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.userselect {
  width: 150px;
  height: 0;
  position: absolute;
  top: 55px;
  left: 20px;
  background-color: white;
  overflow: hidden;
  transition: all 0.5s;
  z-index: 998;
}
#user:hover .userselect {
  height: 100px;
  box-shadow: 0 0 9px rgb(133, 133, 133);
}
li {
  list-style-type: none;
  margin: 7px 10px;
  padding: 10px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s;
  border-radius: 10px;
}
li:hover {
  background-color: rgb(144, 144, 144);
  color: white;
}
</style>
